export function timeout(ms: number, reason = '') {
  return new Promise<number>((_, reject) => {
    setTimeout(() => reject(reason + ' time out'), ms);
  });
}

export function wait(ms: number) {
  return new Promise<number>(resolve => {
    setTimeout(() => resolve(0), ms);
  });
}

export type TAbortablePromise<T> = Promise<T> & { abort: () => void };

/**
 * 把一个普通的promise变成一个可终止的promise。
 */
export function makeAbortable<T>(p: Promise<T>) {
  let abort = () => {};
  let abortPromise = new Promise<T>(
    (_, reject) => (abort = () => reject('Promise abort'))
  );
  let promise: TAbortablePromise<T> = Promise.race([
    p,
    abortPromise,
  ]) as TAbortablePromise<T>;
  promise.abort = abort;
  return promise;
}
